/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package jmmos.gameserver.instancemanager;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Map;
import java.util.logging.Logger;

import javolution.util.FastMap;

import jmmos.Config;
import jmmos.MMODatabaseFactory;
import jmmos.gameserver.model.MMOGuild;
import jmmos.gameserver.model.StatsSet;
import jmmos.gameserver.model.actor.MMOCharacter;
import jmmos.gameserver.model.actor.instance.MMOPcInstance;
import jmmos.gameserver.model.entity.guildhall.GuildHallSiegeEngine;
import jmmos.gameserver.model.entity.guildhall.SiegableHall;
import jmmos.gameserver.model.zone.type.MMOGuildHallZone;
import jmmos.gameserver.network.SystemMessageId;
import jmmos.gameserver.network.serverpackets.SystemMessage;

/**
 * @author BiggBoss
 */
public final class CHSiegeManager
{
	private static final Logger _log = Logger.getLogger(CHSiegeManager.class.getName());
	private static final String SQL_LOAD_HALLS = "SELECT * FROM siegable_guildhall";
	
	private final FastMap<Integer, SiegableHall> _siegableHalls = new FastMap<>();
	
	protected CHSiegeManager()
	{
		loadGuildHalls();
	}
	
	private final void loadGuildHalls()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			Statement s = con.createStatement();
			ResultSet rs = s.executeQuery(SQL_LOAD_HALLS))
		{
			_siegableHalls.clear();
			
			while (rs.next())
			{
				final int id = rs.getInt("guildHallId");
				
				StatsSet set = new StatsSet();
				
				set.set("id", id);
				set.set("name", rs.getString("name"));
				set.set("ownerId", rs.getInt("ownerId"));
				set.set("desc", rs.getString("desc"));
				set.set("location", rs.getString("location"));
				set.set("nextSiege", rs.getLong("nextSiege"));
				set.set("siegeLenght", rs.getLong("siegeLenght"));
				set.set("scheduleConfig", rs.getString("schedule_config"));
				SiegableHall hall = new SiegableHall(set);
				_siegableHalls.put(id, hall);
				GuildHallManager.addGuildHall(hall);
			}
			_log.info(getClass().getSimpleName() + ": Loaded " + _siegableHalls.size() + " conquerable guild halls.");
		}
		catch (Exception e)
		{
			_log.warning("CHSiegeManager: Could not load siegable guild halls!:");
		}
	}
	
	public FastMap<Integer, SiegableHall> getConquerableHalls()
	{
		return _siegableHalls;
	}
	
	public SiegableHall getSiegableHall(int guildHall)
	{
		return getConquerableHalls().get(guildHall);
	}
	
	public final SiegableHall getNearbyGuildHall(MMOCharacter activeChar)
	{
		return getNearbyGuildHall(activeChar.getX(), activeChar.getY(), 10000);
	}
	
	public final SiegableHall getNearbyGuildHall(int x, int y, int maxDist)
	{
		MMOGuildHallZone zone = null;
		
		for (Map.Entry<Integer, SiegableHall> ch : _siegableHalls.entrySet())
		{
			zone = ch.getValue().getZone();
			if ((zone != null) && (zone.getDistanceToZone(x, y) < maxDist))
			{
				return ch.getValue();
			}
		}
		return null;
	}
	
	public final GuildHallSiegeEngine getSiege(MMOCharacter character)
	{
		SiegableHall hall = getNearbyGuildHall(character);
		if (hall == null)
		{
			return null;
		}
		return hall.getSiege();
	}
	
	public final void registerGuild(MMOGuild guild, SiegableHall hall, MMOPcInstance player)
	{
		if (guild.getLevel() < Config.CHS_GUILD_MINLEVEL)
		{
			player.sendMessage("Only guilds of level " + Config.CHS_GUILD_MINLEVEL + " or higher may register for a castle siege");
		}
		else if (hall.isWaitingBattle())
		{
			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.DEADLINE_FOR_SIEGE_S1_PASSED);
			sm.addString(hall.getName());
			player.sendPacket(sm);
		}
		else if (hall.isInSiege())
		{
			player.sendPacket(SystemMessageId.NOT_SIEGE_REGISTRATION_TIME2);
		}
		else if (hall.getOwnerId() == guild.getGuildId())
		{
			player.sendPacket(SystemMessageId.GUILD_THAT_OWNS_CASTLE_IS_AUTOMATICALLY_REGISTERED_DEFENDING);
		}
		else if ((guild.getCastleId() != 0) || (guild.getHideoutId() != 0))
		{
			player.sendPacket(SystemMessageId.GUILD_THAT_OWNS_CASTLE_CANNOT_PARTICIPATE_OTHER_SIEGE);
		}
		else if (hall.getSiege().checkIsAttacker(guild))
		{
			player.sendPacket(SystemMessageId.ALREADY_REQUESTED_SIEGE_BATTLE);
		}
		else if (isGuildParticipating(guild))
		{
			player.sendPacket(SystemMessageId.APPLICATION_DENIED_BECAUSE_ALREADY_SUBMITTED_A_REQUEST_FOR_ANOTHER_SIEGE_BATTLE);
		}
		else if (hall.getSiege().getAttackers().size() >= Config.CHS_MAX_ATTACKERS)
		{
			player.sendPacket(SystemMessageId.ATTACKER_SIDE_FULL);
		}
		else
		{
			hall.addAttacker(guild);
		}
	}
	
	public final void unRegisterGuild(MMOGuild guild, SiegableHall hall)
	{
		if (!hall.isRegistering())
		{
			return;
		}
		hall.removeAttacker(guild);
	}
	
	public final boolean isGuildParticipating(MMOGuild guild)
	{
		for (SiegableHall hall : getConquerableHalls().values())
		{
			if ((hall.getSiege() != null) && hall.getSiege().checkIsAttacker(guild))
			{
				return true;
			}
		}
		return false;
	}
	
	public final void onServerShutDown()
	{
		for (SiegableHall hall : getConquerableHalls().values())
		{
			// Rainbow springs has his own attackers table
			if ((hall.getId() == 62) || (hall.getSiege() == null))
			{
				continue;
			}
			
			hall.getSiege().saveAttackers();
		}
	}
	
	public static CHSiegeManager getInstance()
	{
		return SingletonHolder._instance;
	}
	
	private static final class SingletonHolder
	{
		protected static final CHSiegeManager _instance = new CHSiegeManager();
	}
}